import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.Arrays;

/**
 * Checking stream is able to notify when exactly a socket has been closed.
 *
 * @author Ayzen
 * @version 1.0 30.05.2007 0:00:02
 */
public class CheckingStream extends FilterInputStream {

  private static final int DEFAULT_BUFFER_SIZE = 8192;
  private static final int BUFFER_INCREASE = 1024;

  private int[] buffer;
  private int availableBytes = 0;

  private Vector listeners;

  public CheckingStream(InputStream in) {
    super(in);
  }

  public CheckingStream(InputStream in, StreamListener listener) {
    super(in);
    addStreamListener(listener);
  }

  public void startReading() {
    buffer = new int[DEFAULT_BUFFER_SIZE];
    // Run method in a separate thread, so it won't block current thread
    new Thread(new Runnable() {
      public void run() {
        try {
          reading();
        }
        catch (IOException e) {
          System.out.println("Exception while waiting for data...");
          // Connection has been closed by an exception, that exception could be caused by closing current connection
          e.printStackTrace();
        }
        fireOnClose();
      }
    }, "BinaryReadingThread").start();
  }

  /**
   * The main loop. Reads bytes from a stream and puts them into buffer.
   *
   * @throws IOException on IO error
   */
  private void reading() throws IOException {
    int b = in.read();
    int loadedBytes = 1;
    while (b != -1) {
      synchronized (CheckingStream.this) {
        // Checking if we need to make buffer larger
        if (buffer.length == availableBytes) {
          int[] newBuffer = new int[buffer.length + BUFFER_INCREASE];
          System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
          buffer = newBuffer; 
        }
               
        buffer[availableBytes++] = b;

        // If there no bytes available in the stream we should notify stream listeners
        if (in.available() == 0) {
          fireOnData(loadedBytes);
          loadedBytes = 0;
        }
      }

      b = in.read();
      loadedBytes++;
    }
  }

  public int available() {
    return availableBytes;
  }

  public synchronized int read() throws IOException {
    if (availableBytes == 0)
      return -1;

    availableBytes--;
    int value = buffer[0];

    // Shift all elements left by one
    System.arraycopy(buffer, 1, buffer, 0, buffer.length-1);
    return value;
  }

  public synchronized int read(byte b[], int off, int len) throws IOException {
    if ((off | len | (off + len) | (b.length - (off + len))) < 0)
      throw new IndexOutOfBoundsException();
    else if (len == 0)
      return 0;

    boolean eof = false;
    if (len > availableBytes) {
      len = availableBytes;
      eof = true;
    }

    if (len != 0) {
      for (int i = 0; i < len; i++)
        b[i + off] = (byte) buffer[i];

      availableBytes -= len;
      // Shift all elements left by len
      System.arraycopy(buffer, len, buffer, 0, buffer.length-len);
    }

    return eof ? -1 : len;
  }

  public synchronized long skip(long n) throws IOException {
    if (n == 0)
      return 0;
    
    if (n > availableBytes)
      n = availableBytes;

    availableBytes -= n;
    // Shift all elements left by n
    System.arraycopy(buffer, (int) n, buffer, 0, buffer.length-(int) n);

    return n;
  }

  public void addStreamListener(StreamListener listener) {
    if (listeners == null)
      listeners = new Vector();

    listeners.add(listener);
  }

  public void removeStreamListener(StreamListener listener) {
    if (listeners != null)
      listeners.remove(listener);
  }

  private void fireOnData(int loadedBytes) {
    if (listeners != null)
      for (int i = 0; i < listeners.size(); i++)
        ((StreamListener) listeners.get(i)).onData(CheckingStream.this, loadedBytes);
  }

  private void fireOnClose() {
    if (listeners != null)
      for (int i = 0; i < listeners.size(); i++)
        ((StreamListener) listeners.get(i)).onClose(CheckingStream.this);
  }

}
